// ignore_for_file: prefer_const_constructors

import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flutterdemo/common/calc.dart';
import 'package:flutterdemo/components/avatar.dart';
import 'package:flutterdemo/components/button.dart';
import 'package:flutterdemo/components/my_appbar.dart';
import 'package:flutterdemo/router/router.dart';

class ChatInfo extends StatefulWidget {
  ChatInfo({Key? key}) : super(key: key);

  get keyboardShowCallback => null;

  @override
  _ChatInfoState createState() => _ChatInfoState();
}

class _ChatInfoState extends State<ChatInfo> with WidgetsBindingObserver {
  double bottomHeight = 0;
  double bottomInitHeight = 0;
  double keyHeight = 0;
  double keyHeightPre = 0;
  bool animation = true;
  TextEditingController _inputController = TextEditingController();
  List<String> expression = [
    '😁',
    '😂',
    '😃',
    '😄',
    '😅',
    '😆',
    '😉',
    '😊',
    '😋',
    '😎',
    '😍',
    '😘',
    '😗',
    '😙',
    '😚',
    '😇',
    '😐',
    '😑',
    '😶',
    '😏',
    '😣',
    '😥',
    '😮',
    '😯',
    '😪',
    '😫',
    '😴',
    '😌',
    '😛',
    '😜',
    '😝',
    '😒',
    '😓',
    '😔',
    '😕',
    '😲',
    '😷',
    '😖',
    '😞',
    '😟',
    '😤',
    '😢',
    '😭',
    '😦',
    '😧',
    '😨',
    '😬',
    '😰',
    '😱',
    '😳',
    '😵',
    '😡',
    '😠',
    '💪',
    '👏',
    '📞',
    '💀',
    '💣',
    '👈',
    '👉',
    '👆',
    '👇',
    '✌',
    '✋',
    '👌',
    '👍',
    '👎',
    '👊',
    '👐',
    '✍'
  ];
  FocusNode focusNode = FocusNode();
  // type 0:初始化  1：键盘弹起 2：加号内容 3：表情内容
  int type = 0;
  // 控制显示区的内容
  int showType = 0;

  @override
  void initState() {
    // TODO: implement initState

    super.initState();
    //初始化
    WidgetsBinding.instance!.addObserver(this);

    //输入框焦点
    focusNode.addListener(() {
      if (!focusNode.hasFocus) {
      } else {
        // 获取焦点
        type = 1;
      }
    });
  }

  @override
  void didChangeMetrics() {
    super.didChangeMetrics();
    // 监听键盘高度变化
    WidgetsBinding.instance!.addPostFrameCallback((e) {
      setState(() {
        // bottomHeight = keyHeight;
        animation = false;
        keyHeight = MediaQuery.of(context).viewInsets.bottom;
        if (bottomInitHeight < keyHeight) {
          bottomInitHeight = keyHeight;
        }
        if (type == 1) {
          if (bottomHeight != bottomInitHeight) {
            bottomHeight = keyHeight;
          }
          if (keyHeightPre > keyHeight && (type == 1 || type == 0)) {
            bottomHeight = keyHeight;
          }
        }
        keyHeightPre = keyHeight;
      });
    });
  }

  @override
  void dispose() {
    // TODO: implement dispose
    //销毁
    WidgetsBinding.instance!.removeObserver(this);
    focusNode.dispose();
    super.dispose();
  }

  // 用户聊天内容
  Widget _msgItem(bool ifme) {
    // 聊天消息白色内容区
    List<Widget> contentText = [
      // 三角符号
      Container(
        margin: EdgeInsets.only(top: Calc.width(38)),
        width: 0,
        height: 0,
        decoration: BoxDecoration(
          border: Border(
            // 四个值 top right bottom left
            bottom: BorderSide(
                color: Colors.transparent, width: 6, style: BorderStyle.solid),
            right: BorderSide(
                color: !ifme ? Colors.transparent : Theme.of(context).accentColor,
                width: 12,
                style: BorderStyle.solid),
            left: BorderSide(
                color: ifme ? Colors.transparent : Colors.white,
                width: 12,
                style: BorderStyle.solid),
            top: BorderSide(
                color: Colors.transparent, width: 6, style: BorderStyle.solid),
          ),
        ),
      ),
      SizedBox(
        width: Calc.width(10),
      ),
      Container(
        padding: EdgeInsets.all(Calc.width(20)),
        constraints: BoxConstraints(maxWidth: Calc.width(492)),
        decoration: BoxDecoration(
            color: ifme? Theme.of(context).accentColor : Colors.white,
            borderRadius: BorderRadius.circular(Calc.width(10))),
        child: Text("给哦任何个给哦任何个给哦任何个给哦任何个给哦任何个"),
      )
    ];

    // 聊天内容区
    List<Widget> content = [
      Avatar(
        "https://img0.baidu.com/it/u=1578762854,2915076460&fm=26&fmt=auto",
        size: Calc.width(80),
      ),
      SizedBox(
        width: Calc.width(10),
      ),
      Column(
        crossAxisAlignment:
            ifme ? CrossAxisAlignment.end : CrossAxisAlignment.start,
        children: [
          // 昵称
          _nicknameW(!ifme),
          Row(
            crossAxisAlignment: CrossAxisAlignment.start,
            children: ifme ? contentText.reversed.toList() : contentText,
          ),
        ],
      )
    ];
    return Padding(
      padding: EdgeInsets.only(top: Calc.width(10), bottom: Calc.width(10)),
      child: Row(
        crossAxisAlignment: CrossAxisAlignment.start,
        mainAxisAlignment:
            ifme ? MainAxisAlignment.end : MainAxisAlignment.start,
        children: ifme ? content.reversed.toList() : content,
      ),
    );
  }

  // 用户聊天昵称
  Widget _nicknameW(bool ifshow) {
    if (ifshow) {
      return Container(
        margin: EdgeInsets.only(bottom: Calc.width(5)),
        child: Row(
          children: [
            SizedBox(
              width: Calc.width(10),
            ),
            Text(
              "往事随风",
              style: TextStyle(color: Colors.grey, fontSize: Calc.width(24)),
            ),
            SizedBox(
              width: Calc.width(10),
            ),
          ],
        ),
      );
    } else {
      return Container();
    }
  }

  // 表情内容
  Widget _expressionW() {
    return ListView(
      physics: BouncingScrollPhysics(),
      padding: EdgeInsets.all(Calc.width(20)),
      children: [
        Wrap(
          children: expression
              .map((e) => InkWell(
                    onTap: () {
                      setState(() {
                        _inputController.text += e;
                      });
                    },
                    child: Container(
                      width: Calc.width(88.75),
                      height: Calc.width(88.75),
                      child: Center(
                          child: Text(e,
                              textAlign: TextAlign.center,
                              style: TextStyle(fontSize: Calc.width(50)))),
                    ),
                  ))
              .toList(),
        )
      ],
    );
  }

  // 隐藏键盘
  void _hideKey() {
    FocusScopeNode currentFocus = FocusScope.of(context);
    if (!currentFocus.hasPrimaryFocus && currentFocus.focusedChild != null) {
      FocusManager.instance.primaryFocus!.unfocus();
    }
  }

  // 内容区域
  Widget _contentW() {
    return LayoutBuilder(builder: (context, constraints) {
      return Column(
        children: [
          Container(
            constraints: BoxConstraints(maxHeight: constraints.maxHeight),
            child: ListView.builder(
              itemBuilder: (BuildContext context, int index) {
                return _msgItem(index % 2 == 0);
              },
              itemCount: 30,
              padding: EdgeInsets.fromLTRB(Calc.width(30), Calc.width(10), Calc.width(30), Calc.width(10)),
              reverse: true,
              shrinkWrap: true,
              physics: BouncingScrollPhysics(),
            ),
          )
        ],
      );
    });
  }

  // 底部内容
  Widget _bottomW() {
    return Container(
      padding: EdgeInsets.fromLTRB(
          Calc.width(30), Calc.width(10), Calc.width(30), Calc.width(10)),
      width: double.infinity,
      decoration: BoxDecoration(color: Color.fromRGBO(233, 233, 233, 1)),
      child: Row(
        children: [
          Icon(Icons.settings),
          SizedBox(
            width: Calc.width(10),
          ),
          Expanded(
            child: Container(
                decoration: BoxDecoration(
                    color: Colors.white,
                    borderRadius: BorderRadius.circular(Calc.width(10))),
                constraints: BoxConstraints(maxHeight: Calc.width(250)),
                child: TextField(
                    onChanged: (e) {
                      setState(() {});
                    },
                    controller: _inputController,
                    focusNode: focusNode,
                    decoration: InputDecoration(
                        isDense: true,
                        border: InputBorder.none,
                        contentPadding: EdgeInsets.fromLTRB(Calc.width(10),
                            Calc.width(20), Calc.width(10), Calc.width(20))),
                    maxLines: null,
                    keyboardType: TextInputType.multiline)),
            flex: 1,
          ),
          SizedBox(
            width: Calc.width(10),
          ),
          InkWell(
            onTap: () {
              setState(() {
                animation = true;
                bottomHeight = bottomInitHeight;
                type = 3;
                showType = 3;
                _hideKey();
              });
            },
            child: Icon(Icons.face),
          ),
          SizedBox(
            width: Calc.width(10),
          ),
          AnimatedSwitcher(
            duration: Duration(milliseconds: 300),
            reverseDuration: Duration(milliseconds: 300),
            child: _inputController.text == ""
                ? InkWell(
                    onTap: () {
                      setState(() {
                        animation = true;
                        bottomHeight = bottomInitHeight;
                        type = 2;
                        showType = 2;
                        this._hideKey();
                      });
                    },
                    child: Icon(Icons.add),
                  )
                : MyButton(
                    "发送",
                    height: Calc.width(60),
                    width: Calc.width(150),
                    onPressed: () {
                      _inputController.clear();
                    },
                  ),
          ),
        ],
      ),
    );
  }

  // 底部弹出框
  Widget _bottomContent() {
    return AnimatedContainer(
      curve: Curves.easeInOut,
      width: double.infinity,
      height: bottomHeight,
      child: _bottomRouter(),
      duration: Duration(milliseconds: animation ? 300 : 0),
    );
  }

  // 底部弹出框分出页面路由
  Widget? _bottomRouter() {
    if (showType == 2) {
      // 加号
      return Text("添加图片、视频");
    } else if (showType == 3) {
      // 表情
      return _expressionW();
    }
  }

  @override
  Widget build(BuildContext context) {
    Calc.init(context);
    bottomInitHeight =
        bottomInitHeight == 0 ? Calc.width(550) : bottomInitHeight;
    return GestureDetector(
      onTapDown: (e) {},
      child: Scaffold(
          resizeToAvoidBottomInset: false,
          backgroundColor: Color.fromRGBO(220, 220, 220, 1),
          appBar: MyAppBar().getAppBar("消息"),
          body: Builder(
            builder: (BuildContext ctx) {
              return Column(
                children: [
                  // 聊天内容
                  Expanded(
                    child: GestureDetector(
                      onTapDown: (e) {
                        setState(() {
                          if (keyHeight != 0) {
                            showType = 0;
                          } else {
                            Future.delayed(Duration(milliseconds: 300), () {
                              showType = 0;
                            });
                          }

                          type = 0;
                          animation = true;
                          bottomHeight = 0;
                        });
                        _hideKey();
                      },
                      child: Container(
                        child: _contentW(),
                        color: Colors.transparent,
                      ),
                    ),
                    flex: 1,
                  ),

                  // 底部操作栏
                  _bottomW(),

                  // 底部表情包等空间
                  _bottomContent()
                ],
              );
            },
          )),
    );
  }
}
